package servlet;

import pojo.Major;
import util.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author leiHua
 * @Date 2022/10/14 15:40
 */
@WebServlet("/showAllMajors.do")
public class ShowMajorServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        Connection conn = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtils.getconnection();
            String sql = "SELECT * FROM tb_major";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery(sql);
            Major major = null;
            List<Major> majorList = new ArrayList<>();
            while (rs.next()) {
                String id = rs.getString("id");
                String name = rs.getString("major_name");
                major = new Major();
                major.setMajorName(name);
                major.setId(id);
                majorList.add(major);
            }
            request.setAttribute("majorList", majorList);
            request.getRequestDispatcher("/showAllMajors.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                JDBCUtils.close(rs, ps, conn);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
